package com.blue.Impl.system;

import com.alibaba.fastjson.JSON;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.blue.mapper.system.OperationLogsMapper;
import com.blue.po.system.OperationLogsPO;
import com.blue.service.system.IOperationLogsService;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class OperationLogsServiceImpl extends ServiceImpl<OperationLogsMapper, OperationLogsPO> implements IOperationLogsService {

    @RabbitListener(queues = "operationLogsQueue")
    public void recordOperationLog(String content) {
        OperationLogsPO operationLogsPO = JSON.parseObject(content, OperationLogsPO.class);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        operationLogsPO.setDate(format.format(new Date()));
        //通过ip获取地址
        try {
            //加载配置文件
            ClassPathResource classPathResource = new ClassPathResource("/ip2region/csdn-ip2region.xdb");
            InputStream inputStream = classPathResource.getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            //解析地址
            Searcher searcher = Searcher.newWithBuffer(bytes);
            String region = searcher.search(operationLogsPO.getIp());
            String address = region.replace("|0", "");
            operationLogsPO.setAddress(address);
        } catch (Exception e) {
            operationLogsPO.setAddress("获取ip归属地址失败！");
        }
        this.save(operationLogsPO);
    }
}
